<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加角色按钮 -->
    <el-button type="primary" @click="showAddDialogForm=true">添加角色</el-button>
    <!-- 角色表格 -->
    <el-table :data="rolesList" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            v-for="first in scope.row.children"
            :key="first.id"
            label-position="left"
            inline
            class="demo-table-expand"
            style="border:1px solid red;margin:10px"
          >
            <el-col :span="4">
              <el-tag
                type="success"
                closable
                @close="delRigth(scope.row,first.id)"
              >{{first.authName}}</el-tag>
            </el-col>
            <el-col :span="20">
              <el-row
                v-for="secend in first.children"
                :key="secend.id"
                style="border:1px solid green"
              >
                <el-col :span="4">
                  <el-tag
                    type="info"
                    closable
                    @close="delRigth(scope.row,secend.id)"
                  >{{secend.authName}}</el-tag>
                  <i class="el-icon-edit"></i>
                </el-col>
                <el-col :span="20">
                  <el-tag
                    closable
                    v-for="third in secend.children"
                    :key="third.id"
                    @close="delRigth(scope.row,third.id)"
                  >{{third.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row v-if="scope.row.children.length<=0" style="text-align:center;font-size:18px">没有更多的权限，请去配置</el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit"></el-button>
          <el-button type="danger" icon="el-icon-delete" @click="delRoleById(scope.row.id)"></el-button>
          <el-button type="warning" icon="el-icon-check" @click="configureRights(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加新角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="showAddDialogForm">
      <el-form :model="NewRoleInfo" ref="NewRoleInfo" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="NewRoleInfo.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="NewRoleInfo.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddDialogForm = false">取 消</el-button>
        <el-button type="primary" @click="addNewRole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加分配权限对话框 -->
    <el-dialog title="收货地址" :visible.sync="RightdialogFormVisible">
      <el-tree
        :data="rightList"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="checkedArr"
        :props="defaultProps"
        ref="mytree"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="RightdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantRightForRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getAllRolesList,
  addNewRole,
  delRoleById,
  delRightByRoleId,
  grantRightForRole
} from '@/api/roles_api.js'
import { getAllRightList } from '@/api/right_api.js'
export default {
  data () {
    return {
      rules: {
        roleDesc: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 新角色信息
      NewRoleInfo: {
        roleDesc: '',
        roleName: ''
      },
      // 点击授权当前角色的id
      roleId: '',
      RightdialogFormVisible: false,
      showAddDialogForm: false,
      rolesList: [
        {
          id: null,
          roleName: '',
          roleDesc: ''
        }
      ],
      rightList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      checkedArr: []
    }
  },
  mounted () {
    this.initRole()
  },
  methods: {
    // 初始化所有角色数据源
    initRole () {
      getAllRolesList()
        .then(res => {
        // console.log(res)
          this.rolesList = res.data.data
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 删除角色
    delRoleById (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delRoleById(id)
            .then(res => {
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: res.data.meta.msg
                })
              } else {
                this.$message({
                  type: 'warning',
                  message: res.data.meta.msg
                })
              }
              this.initRole()
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新增角色
    addNewRole () {
      this.showAddDialogForm = false
      addNewRole(this.NewRoleInfo)
        .then(res => {
          if (res.data.meta.status === 201) {
            this.$message({
              type: 'success',
              message: res.data.meta.msg
            })
          } else {
            this.$message({
              type: 'warning',
              message: res.data.meta.msg
            })
          }
          this.initRole()
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 指定角色的指定权限的删除
    delRigth (row, rightId) {
      // console.log(roleId, rightId)
      console.log(row)
      delRightByRoleId(row.id, rightId)
        .then(res => {
          console.log(res)
          if (res.data.meta.status === 200) {
            row.children = res.data.data
            this.$message({
              type: 'success',
              message: res.data.meta.msg
            })
          } else {
            this.$message({
              type: 'error',
              message: '获取数据失败'
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 角色权限树状结构 窗口的展开
    configureRights (row) {
      this.RightdialogFormVisible = true
      // 获取所有权限列表
      getAllRightList('tree')
        .then(res => {
          // console.log(res)
          if (res.data.meta.status === 200) {
            this.rightList = res.data.data
          } else {
            this.$message({
              type: 'warning',
              message: res.data.meta.msg
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
      // 储存当前角色的id
      this.roleId = row.id
      // console.log(row)
      // 获取这个角色所有对应的三级权限id
      // 每次遍历前将之前可能的权限id清空
      this.checkedArr.length = 0
      row.children.forEach((first, index) => {
        if (first.children && first.children.length > 0) {
          first.children.forEach(secend => {
            // 遍历二次权限
            if (secend.children && secend.children.length > 0) {
              secend.children.forEach(third => {
                this.checkedArr.push(third.id)
              })
            }
          })
        }
      })
    },
    // 角色权限树状结构 窗口的展开后默认权限的选择
    //     实现为角色分配权限 >角色授权
    // - 分析接口方法，发现完成这个功能需要两个参数
    //   - roleId:当前角色id
    //   - rids:当前用户所选择所有权限id所组成的字符串，id之间以，分隔，如“1，2，3，4，5”
    grantRightForRole () {
      // console.log(this.$refs.mytree.getCheckedNodes())
      var arr = this.$refs.mytree.getCheckedNodes()
      // console.log(arr)
      //  [{id:109,pid:'107,102},{id:154,pid:'107,102}]
      var temp = []
      arr.forEach((e, i) => {
        temp.push(e.id + ',' + e.pid)
      })
      //   ['109,107,102', '154,107,102']
      //   将temp转换为字符串
      var rids = temp.join(',')
      console.log(rids)
      // 转换成数组去重
      var arr2 = rids.split(',')
      console.log(arr2)
      //   new Set:数组去重 new Set:{109,107,102,154}
      var finalArr = [...new Set(arr2)]
      console.log(finalArr)
      grantRightForRole({ roleId: this.roleId, rids: finalArr.join(',') })
        .then(res => {
          // console.log(res)
          if (res.data.meta.status === 200) {
            getAllRolesList()
              .then(res => {
                // console.log(res)
                this.rolesList = res.data.data
              })
              .catch(err => {
                console.log(err)
              })
            this.$message({
              type: 'success',
              message: res.data.meta.msg
            })
          } else {
            this.$message({
              type: 'warning',
              message: res.data.meta.msg
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
      this.RightdialogFormVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
